<template>
  <div class="content">
    <div v-if="selectedNodeData.previewType" class="header">
      <div
        style="
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          color: var(--color-text-1);
          font-weight: 600;
          font-size: 20px;
          margin-bottom: 10px;
        "
      >
        {{ title }}
      </div>
      <div style="color: rgb(175, 183, 195)">
        {{ selectedNodeData.parentName
        }}<a-divider direction="vertical" />最近编辑:{{
          dayjs(selectedNodeData.updatedAt).format('YYYY-MM-DD HH:mm:ss')
        }}
      </div>
      <a-divider />
    </div>
    <div v-if="selectedNodeData.previewType === 1">
      <!-- <pageHeaderNew :title="title"></pageHeaderNew> -->
      <div class="search-box">
        <div>
          <a-space>
            <a-input-search
              :style="{ width: '420px' }"
              placeholder="搜索"
              style="margin-bottom: 8px; max-width: 240px"
              v-model="searchKey"
            />
          </a-space>
        </div>
      </div>
      <div class="table-box">
        <a-table
          :pagination="false"
          :data="getTreeData"
          show-empty-tree
          style="margin-top: 20px"
          rowKey="id"
        >
          <template #expand-icon="{ expanded }">
            <icon-down v-show="expanded" />
            <icon-right v-show="!expanded" />
          </template>
          <template #columns>
            <a-table-column :width="200" dataIndex="storeName" title="序号">
              <template #cell="{ record }">
                <icon-font
                  :type="
                    !record.downloadPath ? 'icon-wenjianjia' : 'icon-wenjian'
                  "
                  :size="20"
                  style="cursor: pointer; margin-left: 10px"
                />
              </template>
            </a-table-column>

            <a-table-column :width="200" dataIndex="storeName" title="名称">
              <template #cell="{ record }">
                <a-input
                  v-if="isShow && record.id === setFileData.id"
                  :style="{ width: '320px' }"
                  placeholder="Disabled status"
                  v-model="setFileName"
                  :error="isError"
                  @change="changeFileName"
                />
                <div
                  v-else
                  style="
                    white-space: nowrap;
                    text-overflow: ellipsis;
                    overflow: hidden;
                  "
                >
                  {{ record.storeName.split('.')[0] }}
                </div></template
              >
            </a-table-column>
            <!-- <a-table-column :width="200" title="文件类型">
              <template #cell="{record}"> {{ record.storeName.split('.')[1] }}</template>-->
            <a-table-column :width="200" title="文件类型">
              <template #cell="{ record }">
                {{
                  record.fileName
                    ? `.${record.storeName.split('.')[1]}`
                    : '文件夹'
                }}</template
              >
            </a-table-column>

            <a-table-column :width="200" title="创建人">
              <template #cell> {{ '--' }}</template>
            </a-table-column>
            <a-table-column :width="200" title="操作	">
              <template #cell="{ record }">
                <a-space v-if="record.fileName">
                  <a-tooltip content="更多操作">
                    <a-dropdown>
                      <icon-font
                        type="icon-more-def"
                        :size="26"
                        :style="{
                          cursor: 'pointer'
                        }"
                      />
                      <template #content>
                        <a-doption @click="openTabs(record)"
                          >新标签页打开</a-doption
                        >
                        <a-doption @click="copy(record)">复制链接</a-doption>
                        <a-doption @click="goRename(record)">重命名</a-doption>
                        <a-doption @click="setPreview(record)">预览</a-doption>
                        <a-doption @click="SetupCollect(record)"
                          >收藏</a-doption
                        >
                        <a-doption @click="SetupSharing(record)">{{
                          record.shareState === 1 ? '发起共享' : '取消共享'
                        }}</a-doption>
                      </template>
                    </a-dropdown>
                  </a-tooltip>
                  <!-- <a-popconfirm
                    content="确定要删除该文件?"
                    type="error"
                    @ok="delFile(record)"
                  >
                    <a-button type="text" status="danger">删除</a-button>
                  </a-popconfirm> -->
                  <a-tooltip content="删除文件">
                    <a-popconfirm
                      content="确认删除文件?"
                      type="error"
                      @ok="delFile(record)"
                    >
                      <IconFont
                        type="icon-delete"
                        :size="26"
                        :style="{
                          marginRight: '10px',
                          cursor: 'pointer'
                        }"
                      />
                    </a-popconfirm>
                  </a-tooltip>
                </a-space>
                <div v-else type="text" @click="setDocument(record)">
                  {{ '--' }}
                </div>
              </template>
            </a-table-column></template
          >
        </a-table>
      </div>
    </div>
    <div class="Preview" v-if="selectedNodeData.previewType === 2">
      <vue-office-pdf
        :src="selectedNodeData.downloadPath"
        v-if="fileSuffix === 'pdf'"
      />
      <vue-office-docx
        :src="selectedNodeData.downloadPath"
        v-else-if="fileSuffix === 'docx'"
      />
      <vue-office-excel
        :src="selectedNodeData.downloadPath"
        v-else-if="fileSuffix === 'xlsx'"
      />
      <a-image
        width="500"
        height="500"
        v-else
        :src="selectedNodeData.downloadPath"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import UploadModal from './UploadModal.vue';
import FolderModal from './FolderModal.vue';
import {
  PostStorageDisk,
  getFileDelong,
  deleteFile,
  putShareState,
  postFileCollect,
  putFileName,
  getOneknowledgeBase
} from '@/apis/document/documentCenter/index';
import { Message } from '@arco-design/web-vue';
import useClipboard from 'vue-clipboard3';
import mitter from '@/utils/mitt';
import dayjs from 'dayjs';
import VueOfficePdf from '@vue-office/pdf';
import VueOfficeDocx from '@vue-office/docx';
import VueOfficeExcel from '@vue-office/excel';
import { getFileSuffix } from '@/utils/file';

const router = useRouter();
const previewFile = reactive({
  fileShow: false,
  fileMessage: {
    id: '',
    fileName: '',
    downloadUrl: ''
  }
});
const setFileName = ref();
const isShow = ref(false);
const fileType = ref();
const setFileData = ref();
const isError = ref(false);
const PreviewModelVisible = ref(false);
const expandedKeys = ref([]);
const searchKey = ref('');
const userInfo = JSON.parse(localStorage.getItem('userInfo') as any);
const getTreeData = ref<any>([]);
const previewType = ref(0);
const parentName = ref();
const title = ref();
const selectedId = ref();
const selectedNodeData = ref<any>({ previewType: 0 });
const fileSuffix = ref();
const getSelectedNodeData = (data) => {
  title.value = data.storeName;
  selectedNodeData.value = data;
  console.log(2, data);
  if (data.previewType === 2)
    fileSuffix.value = getFileSuffix(data.downloadPath);
};
mitter.on('PreviewData', (val: any) => {
  console.log(1, val);
  getSelectedNodeData(val);
});
const { toClipboard } = useClipboard();

const tree = (data: any) => {
  data.forEach((element: any) => {
    element.children = element.children || [];
    if (element.children) tree(element.children);
  });
  return data;
};

const setTreeData = (data: any) => {
  data.forEach((item: any) => {
    if (item.file) {
      item.file.forEach((ele: any) => {
        item.children.push({ ...ele, storeName: ele.useFileName, type: 1 });
      });
    }
    if (item.children) setTreeData(item.children);
  });
  return data;
};

const getTableData = async () => {
  try {
    const res = await getOneknowledgeBase({ id: selectedNodeData.value.id });
    getTreeData.value = setTreeData([{ ...res }]);
  } catch (err: unknown) {
    console.log(err);
  }
};

const setDocument = async (val: any) => {
  try {
    console.log(val);
    if (!val.id) await PostStorageDisk({ ...val });
    getTableData();
  } catch (err: unknown) {
    console.log(err);
  }
};

const setPreview = (val: any) => {
  previewFile.fileMessage.id = val.id;
  previewFile.fileMessage.fileName = val.fileName;
  previewFile.fileMessage.downloadUrl = val.downloadPath;
  previewFile.fileShow = true;
  PreviewModelVisible.value = true;
};

const delFile = async (res: any) => {
  try {
    await deleteFile({ id: res.id, type: 0 });
    getTableData();
  } catch (err: unknown) {
    console.log(err);
  }
};

const SetupSharing = async (val: any) => {
  try {
    await putShareState({ id: val.id });
    getTableData();
  } catch (err: unknown) {
    console.log(err);
  }
};

const setHide = (res: boolean) => {
  if (res) getTableData();
  expandedKeys.value = [];
};

const SetupCollect = async (record: any) => {
  try {
    await postFileCollect({ userId: userInfo.id, fileId: record.id });
    getTableData();
  } catch (err: unknown) {
    console.log(err);
  }
};

const copy = async (res) => {
  try {
    await toClipboard(res.downloadPath);
    Message.success('复制成功');
  } catch (err: unknown) {
    console.log(err);
  }
};

const goRename = async (res: any) => {
  setFileName.value = res.storeName.split('.')[0];
  fileType.value = res.storeName.split('.')[1];
  setFileData.value = res;
  isShow.value = true;
  console.log(setFileData.value, fileType.value, setFileName.value);
};

const changeFileName = async (e: string) => {
  try {
    if (setFileName.value === '') {
      isError.value = true;
      return;
    }
    await putFileName({
      useFileName: `${setFileName.value}.${fileType.value}`,
      id: setFileData.value.id
    });
    getTableData();
    setFileName.value = undefined;
    fileType.value = undefined;
    setFileData.value = undefined;
    isShow.value = false;
    isError.value = false;
  } catch (err: unknown) {
    console.log(err);
  }
};

const openTabs = (res) => {
  router.push({ name: 'FileTabsPage', query: { url: res.downloadPath } });
};

watchEffect(() => {
  if (selectedNodeData.value.previewType === 1) {
    getTableData();
  }
});
</script>

<style scoped lang="less">
.content {
  padding: 10px;
  height: 100%;
  width: 100%;
}

.search-box {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  width: 96%;
  margin: 10px;
}

:deep(.arco-table-tr) {
  height: 40px;
}
:deep(.arco-table-th) {
  font-weight: bold;
  // font-size: 13px;
}

.Preview {
  width: 100%;
  height: 100%;
  overflow: auto;
  padding: 20px;
  display: flex;
  justify-content: center;
}
</style>
